package is.ru.honn.rupin.data;

import is.ru.honn.rupin.domain.Pin;
import is.ruframework.data.RuData;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Sigrún Inga Kristinsdóttir.
 * Date: 18.10.2012
 * Time: 15:10
 * copyright (c) sigruninga&susanne
 *
 * @author Sigrún Inga kristindóttir og Susanne Götz
 * @version 1.1
 */

/**
 * Gagnagrunnstengin fyrir pins.
 */

public class PinData extends RuData implements PinDataGateway
{
    /**
     * Fall sem skráir upplýsingar um Pin í gagnagrunn.
     * @param pin
     */
    public void add(Pin pin) {
        SimpleJdbcInsert insertPin = new SimpleJdbcInsert(getDataSource()).withTableName("ru_pins");

        Map<String, Object> parameters = new HashMap<String, Object>(5);
        parameters.put("description", pin.getDescription());
        parameters.put("link", pin.getLink());
        parameters.put("image", pin.getImage());
        parameters.put("boardname", pin.getBoard());
        parameters.put("username",  pin.getCreator());

        try
        {
            insertPin.execute(parameters);
        }
        catch (DataIntegrityViolationException divex)
        {
            log.warning("Duplicate entry");
        }

    }

    /**
     * Fall sem sækir allar pinnar sem tengt eru board með nafni "boardname".
     * @param boardname
     * @return Lista af pinnum
     */
    public List<Pin> getPinsByBoard(String boardname) {
        JdbcTemplate queryContent = new JdbcTemplate(getDataSource());
        String sql = "select * from ru_pins where boardname = ?";
        List<Pin> pins = queryContent.query(sql, new Object[]{boardname}, new PinRowMapper());
       /* for (Pin p : pins)
        {
            System.out.println(p.getDescription());
        }*/
        return pins;
    }
}
